#include <math.h>
#include <dalelib/graphics/texture.h>
#include <dalelib/utils/daleassert.h>

namespace dalelib
{

bool Texture::very_first = true;

int Texture::load(const string _Name, const bool _Keep )
{
//	if( very_first ) { very_first = false; ilInit(); } // lazy devil init


//	ILenum Error;
//	while ((Error = ilGetError()) != IL_NO_ERROR)
//	{
//		printf("%d: %s/n", Error, iluErrorString(Error));
//	}

	if( _first ) { _first = false; glGenTextures( 1, &_handle ); }

	ILuint il_id;
	ilGenImages( 1, &il_id );
	ilBindImage( il_id );
	ILboolean success = ilLoadImage( _Name.c_str() );

	if( success )
	{
		_width = ilGetInteger(IL_IMAGE_WIDTH);
		_height = ilGetInteger(IL_IMAGE_HEIGHT);
		_bytes_per_pixel = ilGetInteger(IL_IMAGE_BPP);
		_image_format = ilGetInteger(IL_IMAGE_FORMAT);

		if( _Keep )
		{
			_pixel_data = new unsigned char[_width*_height*_bytes_per_pixel];
			memcpy( _pixel_data, ilGetData(), _width*_height*_bytes_per_pixel*sizeof(unsigned char) );
		}

//			ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
		bind();

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
//        glCompressedTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());

		ilDeleteImages( 1, &il_id );
		return 0;
	}
	else
	{
		ilDeleteImages( 1, &il_id );
		return -1;
	}
}


void Texture::bind()
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, _handle);
}

void Texture::unbind()
{
	glBindTexture(GL_TEXTURE_2D, 0);
//	glDisable(GL_TEXTURE_2D);
}

} // namespace dalelib
